/**
 * (created at 2011-1-23)
 */
package qiushuo.mysqlparser.ast.expression.primary.function.cast;

import java.util.List;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.ast.expression.primary.function.FunctionExpression;
import qiushuo.mysqlparser.generator.SQLType;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class Convert extends FunctionExpression {
    /**
     * Either {@link transcodeName} or {@link typeName} is null
     */
    private final String transcodeName;
    private final String typeName;
    private final Expression typeInfo1;
    private final Expression typeInfo2;

    public Convert(Expression arg, String transcodeName) {
        super("CONVERT", wrapList(arg));
        if (null == transcodeName) {
            throw new IllegalArgumentException("transcodeName is null");
        }
        this.transcodeName = transcodeName;
        this.typeName = null;
        this.typeInfo1 = null;
        this.typeInfo2 = null;
    }

    public Convert(Expression arg, String typeName, Expression typeInfo1, Expression typeInfo2) {
        super("CONVERT", wrapList(arg));
        this.transcodeName = null;
        if (null == typeName) {
            throw new IllegalArgumentException("typeName is null");
        }
        this.typeName = typeName;
        this.typeInfo1 = typeInfo1;
        this.typeInfo2 = typeInfo2;
    }

    @Override
    public FunctionExpression constructFunction(List<Expression> arguments) {
        throw new UnsupportedOperationException("function of char has special arguments");
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            sb.append("Convert(").append(getArguments(0));
            if (transcodeName != null) {
                sb.append(" USING ").append(transcodeName);
            } else {
                sb.append(", ").append(typeName);
                if (typeInfo1 != null) {
                    sb.append("(").append(typeInfo1.generateSql(type));
                    if (typeInfo2 != null) {
                        sb.append(", ").append(typeInfo2.generateSql(type));
                    }
                    sb.append(")");
                }
            }
            sb.append(")");
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }

}
